package com.hd123.rumba.qt.def;

import java.util.StringTokenizer;

public class ScopeExpression {
  public static String scopeExpToSQLExp(String strWhat, String scopeExp, boolean quoted) {
    StringBuffer sb = new StringBuffer();
    strWhat = strWhat.replaceAll(" ", "");
    scopeExp = scopeExp.replaceAll(" ", "");

    if (scopeExp.equals(RANGE)) {
      sb.append(strWhat);
      sb.append(" = ");
      sb.append(quoteSingle(RANGE, true));
    } else if (strWhat.trim().length() > 0 && scopeExp.trim().length() > 0) {
      StringTokenizer st = new StringTokenizer(scopeExp, ",");
      sb.append("(");
      while (st.hasMoreTokens()) {
        sb.append(strWhat);
        String str = st.nextToken();
        if (str.trim().length() != 0) {
          int i = str.indexOf(RANGE);
          if (i < 0) {
            sb.append("=");
            sb.append(quoteSingle(str, quoted));
          } else {
            sb.append(" between ");
            sb.append(quoteSingle(str.substring(0, i), quoted));
            sb.append(" and ");
            sb.append(quoteSingle(str.substring(i + RANGE.length()), quoted));
          }
          if (st.hasMoreTokens())
            sb.append(" or ");
        }
      }
      sb.append(")");
    }
    return sb.toString();
  }

  private static String quoteSingle(String s, boolean quoted) {
    if (quoted)return "'" + s.replace("'", "''") + "'"; else return s;
  }

  private static String RANGE = "...";
}
